<?php

namespace App\Http\Controllers\Api\Organization;

use App\Http\Controllers\Admins\BaseAdminController;
use App\Http\Controllers\Controller;
use App\Models\Activity;
use App\Models\OrganizationsMembersExamine;
use App\Models\Posts;
use App\Models\Organization;
use App\Models\OperationalLogs;
use App\Models\OrganizationsMembers;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrganizationController extends Controller

{
    /**
     * 全部组织
     * @param Request $request
     * @return array
     *
     */
    public function lists(Request $request): array
    {

        $where = array();
        $type = request('type',null);            // 同城
        $orderBy = '';
        if ($type) {
            if($type == 1){     //推荐
                $orderBy = 'sort';
            }elseif($type == 2){        // 全部
                $orderBy = 'all';
            }elseif($type == 3){
                 $where['type'] = 1;
            }elseif($type == 4){
                $where['type'] = 2;
            }
        }

        $name = request('name',null);                  // 按名称搜索
        if ($name) {
            $where[] = ['name','like',"$name%"];
        }


        $where['status']  = 1;

        $data = Organization::getDataList($where,$orderBy);
        $result = array();
        if($data){
            foreach ($data as $val){
                $result[] = Organization::getDataByID($val['id']);
            }
        }
        return ret($result);
    }


    public function introduction(){

        $id = request('id',null);
        $where = [
            'id'=>$id,
        ];
        $model = Organization::query();
        ModelQuery($id,$model,$where);
        $base_info = Organization::query()->where($where)->first();

        return ret($base_info);

    }

    /**
     * 组织详情
     * 
ALTER TABLE `activity`
ADD COLUMN `organizations_id`  int(11) NULL COMMENT '活动所属组织' AFTER `id`;
ALTER TABLE `posts`
ADD COLUMN `organizations_id`  int(10) NULL COMMENT '组织ID' AFTER `image`;
ALTER TABLE `organizations`
ADD COLUMN `notice`  text NULL COMMENT '通知、公告' AFTER `name`;

     * @return array
     */
    public function detail(): array
    {
        $id = request('id',null);
        $where = [
            'id'=>$id,
        ];
        $model = Organization::query();
        ModelQuery($id,$model,$where);
        $base_info = Organization::getDataByID($id);

        $base_info['is_admin']  =  0;
        if(!empty($base_info) && !empty($base_info['create_user_id']) ){
            $user = auth('api')->user();
            if(!empty($user['id']) && $base_info['create_user_id'] == $user['id']){

                $base_info['is_admin']  =  1;
            }

            $base_info['avatar']  =  getImageUrl($base_info['avatar']);
        }
        //组织成员
        $membersList = OrganizationsMembers::getMembersList($id);
        if ($membersList['code'] != 200) {
            $members = ['total'=>0,[]];
        }else{
            $members = ['total'=>count($membersList['data']),'list'=>$membersList['data']];
        }

        //活动
        $whereActivity = ['organizations_id'=>$id];
        $fieldActivity = [
            'id',
            'name',
            'image',
            'signup_status',
            'signup_start_at',
            'signup_end_at',
            'start_at',
            'end_at',
            'status',
            'detail',
            'start_at',
            'end_at'
        ];
        $activityList = Activity::getActivityListByWhere($whereActivity,$fieldActivity);
        $activityListRes = array();
        foreach ($activityList as $k => $v) {
            $activityListRes[] = Activity::formatListData($v);
        }
        $activity = ['total'=>count($activityList),'list'=>$activityListRes];

/*        $activityListRes = array();
        if($activityList){
            $tmpArr = [];
            foreach ($activityList as $val){

                $month = date('Y年m月',strtotime($val['start_at']));
                $tmpArr[$month][] = Activity::formatListData($val);
            }

            foreach ($tmpArr as $k => $v) {
                $activityListRes[] = ['month'=>$k,'list'=>$v];
            }
        }


        $activity = ['total'=>count($activityList),'list'=>$activityListRes];*/





        //帖子
        $wherePosts = ['organizations_id'=>$id,'status'=>1];
        $fieldPosts = [
            'id',
            'title',
            'content',
            'image',
            'comment_counts',
            'created_at'
        ];
        $postsList = Posts::getPostsListByWhere($wherePosts,$fieldPosts);
        $tempArr = array();
        foreach($postsList as $key=>$val){

            $tempArr[] = Posts::getDataByID($val['id']);
        }
        $posts = ['total'=>count($postsList),'list'=>$tempArr];

        $data = [
            'base_info'=>$base_info,
            'members' => $members,
            'activity' => $activity,
            'posts' => $posts,
        ];
        return ret($data);
    }


    /**
     * 申请加入组织
     *
     * ALTER TABLE `organizations_members`
CHANGE COLUMN `name` `organization_id`  int(10) NOT NULL COMMENT '组织ID' AFTER `id`,
CHANGE COLUMN `status` `user_id`  int(10) NOT NULL COMMENT '用户ID' AFTER `organization_id`,
CHANGE COLUMN `sort` `is_admin`  tinyint(3) NOT NULL DEFAULT 0 COMMENT '是否管理员1是0否' AFTER `user_id`,
ADD COLUMN `status`  tinyint(3) NOT NULL DEFAULT 1 COMMENT '状态：0被删除1申请中2审核通过' AFTER `is_admin`;


     */
    public function join(): array
    {
        $organization_id = request('organization_id',null);

        $userInfo = auth('api')->user();

        $res = OrganizationsMembers::applicationJoin($userInfo,$organization_id);

        if ($res['code'] != 200) {
            return ret($res['data'],$res['code'],$res['msg']);
        }
        unset($res['code']);
        unset($res['msg']);
        return ret($res);

    }

    /**
     * 组织成员审核
     * 0被删除(不通过)1申请中2审核通过
     *
     */
    public function examineAndVerify(): array
    {
        $om_id = request('om_id',null);
        $status = request('status',null);

        $res = OrganizationsMembers::updateJoinStatus($om_id,$status);

        if ($res['code'] != 200) {
            return ret($res['data'],$res['code'],$res['msg']);
        }
        unset($res['code']);
        unset($res['msg']);
        return ret($res);

    }


    public function applicationList()
    {

        $userInfo = auth('api')->user();
        $userId  = $userInfo['id'];
        $where['user_id'] = $userId;
        $where['is_admin'] = 1;
        $where['status'] = 2;
        $friends  =  OrganizationsMembers::query()->where($where)->with(['orgList'])->get();

        $data = array();
        if($friends){
            foreach ($friends as $key=>$val){
                if(!empty($val['orgList'])){

                    //查询需要审核的消息
                    $alist = OrganizationsMembers::getApplicationList($val['organization_id']);
                    $data[] = [
                        'id'=>$val['id'],
                        'organization_id'=>$val['organization_id'],
                        'is_admin'=>$val['is_admin'],
                        'name'=>$val['orgList']['name'],
                        'applicationList'=>$alist,
                    ];
                }
            }
        }
        $result = [
            'data'=>array_values($data)
        ];
        return ret($result);
    }

    #组织成员
    public function members(): array
    {
        $organization_id = request('organization_id',null);
        $is_all = request('is_all',null);
        $is_examine = request('is_examine',null);

        $res = OrganizationsMembers::getMembersList($organization_id,$is_all,$is_examine);

        if ($res['code'] != 200) {
            return ret($res['data'],$res['code'],$res['msg']);
        }
        foreach($res['data'] as $key=>$val){
            $res['data'][$key]['avatar'] = getImageUrl($val['avatar']);
        }

        unset($res['code']);
        unset($res['msg']);
        return ret($res['data']);
    }

    #我的组织（我加入的组织）
    public function mine()
    {

        $userInfo = auth('api')->user();
        $userId  = $userInfo['id'];

        //组织成员
        $membersList = OrganizationsMembers::getMyMembersList($userId);

        $result = array();
        foreach ($membersList as $val){
            $result[] = OrganizationsMembers::formatListDataOne($val);
        }

        return ret($result);
    }


    /**
     * 创建组织
     */
    public function addOrganization()
    {
        $post = request()->only('name','notice','avatar','create_user_id','create_nickname','create_phone');
        $user = auth('api')->user();
        if(!$post['name']){
            return retError('缺少名称');
        }

        $post['create_user_id'] = $user['id'];

        DB::beginTransaction();
        try {
            $post['first_letter'] =  getHanziInitial($post['name']);
            $post['status'] = 0;    //默认为待审核状态
            Organization::query()->create($post);

/*            $list = Organization::query()->where($post)->first();
            if($list){
                $arr = array();
                $arr['organization_id'] =$list['id'];
                $arr['is_admin'] = 1;
                $arr['user_id'] = $user['id'];
                OrganizationsMembers::query()->create($arr);
            }*/

            DB::commit();
            return ret('操作成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

/***
 * @return array
 *    修改组织信息
 *
 */
    public function editOrganization()
    {
        $post = request()->only('id','name','avatar','create_nickname','create_phone','avatar','notice');
        $user = auth('api')->user();
        if(!$post['id']){
            return retError('缺少ID');
        }

        $data = DB::table('organizations')->where( ["id"=>$post['id'], 'create_user_id'=>$user['id'] ])->first();

        if(!$data){
            return retError("组织不存在或者权限不足");
        }

        DB::beginTransaction();
        try {
            Organization::query()->where(  ["id"=>$post['id'], 'create_user_id'=>$user['id'] ] )->update($post);
            DB::commit();
            return ret('更新成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }




    public function menuList(Request $request) :array
    {

        $return = array();

        $return[0]['name'] =  '推荐';
        $return[0]['type'] =  '1';

        $return[1]['name'] =  '全部';
        $return[1]['type'] =  '2';

        $return[2]['name'] =  '院系';
        $return[2]['type'] =  '3';

        $return[3]['name'] =  '地方';
        $return[3]['type'] =  '4';
        return ret($return);
    }

    /***
     * @return array
     * 转让管理员
     */
    public function transferStatus()
    {
        $post = request()->only('id','transfer_id');
        $user = auth('api')->user();
        if(!$post['id']){
            return retError('缺少ID');
        }

        $data = DB::table('organizations')->where( ["id"=>$post['id'], 'create_user_id'=>$user['id'] ])->first();

        if(!$data){
            return retError("组织不存在或者权限不足");
        }

        DB::beginTransaction();
        try {

            $arr = array();
            $arr['organization_id'] =$post['id'];
            $arr['user_id'] = $user['id'];
           // $arr['transfer_id'] = $post['transfer_id'];
            $arr['status'] = 1;
            //添加 申请
            OrganizationsMembersExamine::query()->create($arr);

            //取消
            OrganizationsMembers::query()->where(['organization_id'=>$post['id'],'user_id'=>$user['id'],'is_admin'=>1  ])->update( ['is_admin'=>0] );
            Organization::query()->where(['id'=>$post['id']])->update( ['create_user_id'=>19] );

            DB::commit();
            return ret('申请成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

}
